package com.banshuibao.bsb_android.download;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.banshuibao.bsb_android.MyApplication;
import com.banshuibao.bsb_android.R;
import com.banshuibao.bsb_android.adapter.DownloadingAudioAdapter;
import com.banshuibao.bsb_android.fragment.BaseFragment;
import com.banshuibao.bsb_android.model.DownloadAudioModel;
import com.banshuibao.bsb_android.util.CCMediaConfig;
import com.banshuibao.bsb_android.util.DataSet;
import com.banshuibao.bsb_android.util.MediaUtil;
import com.banshuibao.bsb_android.util.ParamsUtil;
import com.banshuibao.bsb_android.util.XToast;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloader;

import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 下载中标签页
 *
 * @author CC视频
 */
public class DownloadingAudioFragment extends BaseFragment {

    private Context context;

    private ListView downloadingListView;
    private List<DownloadAudioModel> downloadingInfos;
    private DownloadingAudioAdapter downloadAdapter;
    private DownloadedReceiver receiver;
    private LinearLayout bottomLayout;
    private TextView all, delete;
    private HashMap<String, String> deletes;
    private TextView menu;
    private boolean isCheckModel;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = getActivity();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(CCMediaConfig.ACTION_AUDIO_DOWNLOADING);
        intentFilter.addAction(CCMediaConfig.ACTION_AUDIO_DOWNLOADED);
        receiver = new DownloadedReceiver();
        context.registerReceiver(receiver, new IntentFilter(intentFilter));
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return LayoutInflater.from(context).inflate(R.layout
                .fragment_downloading, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(view);
        updateData();
    }

    private void initView(View view) {
        downloadingListView = view.findViewById(R.id.listView);
        downloadingListView.setDivider(null);
        bottomLayout = view.findViewById(R.id.bottom_layout);
        all = view.findViewById(R.id.all);
        delete = view.findViewById(R.id.delete);
        downloadAdapter = new DownloadingAudioAdapter(context);
        downloadingListView.setAdapter(downloadAdapter);
        menu = getActivity().findViewById(R.id.menu);
        menu.setOnClickListener(l);
        all.setOnClickListener(l);
        delete.setOnClickListener(l);

        deletes = new HashMap<>();
        downloadingInfos = new ArrayList<>();
        downloadingListView.setOnItemClickListener(onItemClickListener);
    }

    private synchronized void updateData() {
        if (downloadingInfos == null) {
            return;
        }
        downloadingInfos.clear();
        List<DownloadAudioModel> downloadInfos = DataSet.getDownloadAudioInfos();
        for (DownloadAudioModel downloadInfo : downloadInfos) {

            if (downloadInfo.getStatus() == DownloadAudioModel.FINISH) {
                continue;
            }
            String path = getFilePath(downloadInfo.getUuid());
            if (TextUtils.isEmpty(path))
                return;
            if (downloadInfo.getIndexTask() == 0) {
                downloadInfo.setIndexTask(startTask(path, downloadInfo.getUrl(), downloadInfo.getUuid()));
            }
            downloadingInfos.add(downloadInfo);
        }
        if (downloadAdapter != null)
            downloadAdapter.setData(downloadingInfos);
    }

    private String getFilePath(String uuid) {
        String userId = MyApplication.applicationInstance.getLoginInfo().getUserId();
        File file = MediaUtil.createAudioFile(CCMediaConfig.DOWNLOAD_DIR + userId, uuid);
        if (file == null)
            return "";
        return file.getPath();
    }

    private int startTask(String path, String url, String tag) {
        return FileDownloader.getImpl().create(url)
                .setPath(path)
                .setListener(new FileDownloadListener() {

                    private long contentLength = 0;

                    @Override
                    protected void pending(final BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        if (!(totalBytes <= 0)) {
                            contentLength = totalBytes;
                        } else
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        URL url = new URL(task.getUrl());
                                        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                                        contentLength = connection.getContentLength();
                                        connection.disconnect();
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }).start();
                    }

                    @Override
                    protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        updateProgress(task, soFarBytes, totalBytes, contentLength);
                    }

                    @Override
                    protected void completed(BaseDownloadTask task) {
                        String uuid = (String) task.getTag();
                        int totalBytes = task.getSmallFileTotalBytes();
                        String progressText = ParamsUtil.byteToKB(totalBytes) + "KB/" + ParamsUtil.byteToKB(totalBytes) + "KB";
                        DownloadAudioModel downloadAudioModel = DataSet.getDownloadAudioInfo(uuid);
                        if (downloadAudioModel == null)
                            return;
                        downloadAudioModel.setStatus(DownloadAudioModel.FINISH);
                        downloadAudioModel.setProgressText(progressText);
                        DataSet.updateDownloadAaudioInfo(downloadAudioModel);
                        updateData();
                        if (getActivity() != null) {
                            getActivity().sendBroadcast(new Intent(CCMediaConfig.ACTION_AUDIO_DOWNLOADED));
                        }
                        DataSet.saveData();
                    }

                    @Override
                    protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {

                    }

                    @Override
                    protected void error(BaseDownloadTask task, Throwable e) {
                        XToast.showToast(MyApplication.applicationInstance, "音频下载失败");
                        String uuid = (String) task.getTag();
                        DownloadAudioModel downloadAudioModel = DataSet.getDownloadAudioInfo(uuid);
                        if (downloadAudioModel == null)
                            return;
                        downloadAudioModel.setStatus(DownloadAudioModel.PAUSE);
                        DataSet.updateDownloadAaudioInfo(downloadAudioModel);
                        updateData();
                    }

                    @Override
                    protected void warn(BaseDownloadTask task) {
                    }
                }).setTag(tag).
                        setMinIntervalUpdateSpeed(400).
                        start();
    }


    private void updateProgress(BaseDownloadTask task, int soFarBytes, int totalBytes, long contentLength) {
        if (totalBytes <= 0)
            totalBytes = task.getSmallFileTotalBytes();
        if (totalBytes <= 0)
            totalBytes = (int) contentLength;
        if (totalBytes <= 0)
            return;
        String uuid = (String) task.getTag();
        DownloadAudioModel downloadAudioModel = DataSet.getDownloadAudioInfo(uuid);
        if (downloadAudioModel == null)
            return;
        double progress = (double) soFarBytes / (double) totalBytes * 100;
        String progressText = ParamsUtil.byteToKB(soFarBytes) + "KB/" + ParamsUtil.byteToKB(totalBytes) + "KB";
        downloadAudioModel.setProgress(progress);
        downloadAudioModel.setProgressText(progressText);
        DataSet.updateDownloadAaudioInfo(downloadAudioModel);
        for (DownloadAudioModel downloadAudioModel1 : downloadingInfos) {
            if (downloadAudioModel.getUuid().equals(downloadAudioModel1.getUuid())) {
                int index = downloadingInfos.indexOf(downloadAudioModel1);
                DownloadAudioModel downloadAudioModel2 = downloadingInfos.get(index);
                downloadAudioModel2.setProgress(progress);
                downloadAudioModel2.setProgressText(progressText);
                downloadingInfos.set(index, downloadAudioModel2);
                break;
            }
        }
        if (downloadAdapter != null)
            downloadAdapter.notifyDataSetChanged();
    }


    private OnItemClickListener onItemClickListener = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            if (downloadAdapter == null)
                return;
            DownloadAudioModel downloadInfo = downloadAdapter.getItem(position);
            if (isCheckModel) {
                downloadInfo.setCheck(!downloadInfo.isCheck());
                if (downloadInfo.isCheck())
                    deletes.put(downloadInfo.getUuid(), downloadInfo.getUrl());
                else
                    deletes.remove(downloadInfo.getUuid());
                updateDeletesText();
                downloadAdapter.notifyDataSetChanged();
            } else {
                if (downloadInfo.getStatus() == DownloadAudioModel.DOWNLOAD) {
                    downloadInfo.setStatus(DownloadAudioModel.PAUSE);
                    FileDownloader.getImpl().pause(downloadInfo.getIndexTask());
                } else {
                    downloadInfo.setStatus(DownloadAudioModel.DOWNLOAD);
                    downloadInfo.setIndexTask(startTask(getFilePath(downloadInfo.getUuid()), downloadInfo.getUrl(), downloadInfo.getUuid()));
                }
                DataSet.updateDownloadAaudioInfo(downloadInfo);
                downloadAdapter.notifyDataSetChanged();
            }
        }
    };

    private View.OnClickListener l = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.all:
                    int listSize = downloadAdapter.getList().size();
                    if (listSize == 0)
                        return;
                    int deleteSize = deletes.size();
                    if (deleteSize >= listSize) {
                        for (int i = 0; i < listSize; ++i) {
                            downloadAdapter.getList().get(i).setCheck(false);
                        }
                        deletes.clear();
                    } else {
                        for (int i = 0; i < listSize; ++i) {
                            DownloadAudioModel downloadInfo = downloadAdapter.getList().get(i);
                            downloadInfo.setCheck(true);
                            deletes.put(downloadInfo.getUuid(), downloadInfo.getUrl());
                        }
                    }
                    updateDeletesText();
                    downloadAdapter.notifyDataSetChanged();
                    break;
                case R.id.delete:
                    if (deletes.size() == 0) {
                        return;
                    }
                    for (HashMap.Entry<String, String> entry : deletes.entrySet()) {
                        delete(entry.getKey(), entry.getValue());
                    }
                    deletes.clear();
                    updateDeletesText();
                    downloadAdapter.notifyDataSetChanged();
                    break;
                case R.id.menu:
                    setCheckModel();
                    break;
            }
        }
    };

    public void setCheckModel() {
        if (isHidden())
            return;
        isCheckModel = !isCheckModel;
        if (isCheckModel) {
            bottomLayout.setVisibility(View.VISIBLE);
            menu.setText("取消");
        } else {
            menu.setText("管理");
            setClearDelete();
        }
        downloadAdapter.setShowCheck(isCheckModel);
    }

    private void setClearDelete() {
        bottomLayout.setVisibility(View.GONE);
        menu.setText("管理");
        isCheckModel = false;
        int size = downloadAdapter.getList().size();
        for (int i = 0; i < size; ++i) {
            downloadAdapter.getList().get(i).setCheck(false);
        }
        deletes.clear();
        updateDeletesText();
        downloadAdapter.setShowCheck(isCheckModel);
    }

    private void updateDeletesText() {
        delete.setText(String.valueOf("删除" + "(" + deletes.size() + ")"));
    }

    private void delete(String uuid, String url) {
        FileDownloader.getImpl().create(url).pause();
        DataSet.removeDownloadAudioInfo(uuid);
        File file = MediaUtil.getMediaFile(CCMediaConfig.DOWNLOAD_DIR, uuid);
        if (file.exists()) {
            file.delete();
        }
        updateData();
    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!isHidden()) {
            if (getActivity() != null) {
                menu = getActivity().findViewById(R.id.menu);
                menu.setOnClickListener(l);
            }
        }
        if (hidden) {
            setClearDelete();
        }
    }

    private class DownloadedReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            updateData();
        }
    }


    @Override
    public void onDestroy() {
        context.unregisterReceiver(receiver);
        if (downloadAdapter != null) {
            downloadAdapter.clear();
            downloadAdapter = null;
        }
        super.onDestroy();
    }

}
